package orxatas.travelme.activity;

import java.util.ArrayList;
import java.util.List;

import orxatas.travelme.databases.exceptions.PlaceNotInLocal;
import orxatas.travelme.entity.Geopoint;
import orxatas.travelme.entity.Place;
import orxatas.travelme.entity.PlaceType;
import orxatas.travelme.manager.PlaceManager;
import orxatas.travelme.sync.AsyncNoticeCode;
import orxatas.travelme.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.ItemizedOverlay;

import android.location.*;

public class MapPlaceActivity extends MapActivity implements AsyncActivity{
	private final static String TAG = "TravelMe - MapPlacesActivity";
	private MapView mapView;
	private MapController mapController;
	private LocationManager locationManager;
	private int inicialZoom = 16;

	private int idPlaceSelected;
	private MyOverlay myPositoinOverlay = null;
	private Place place;

	@Override
	protected void onCreate(Bundle arg0) {

		super.onCreate(arg0);
		
		this.setContentView(R.layout.map_places);

		idPlaceSelected = getIntent().getIntExtra("id_place", -1);
		if(idPlaceSelected == -1) {
	    	Log.e(TAG, "Fallo al iniciar la actividad. No se especifico el id de lugar.");
	    	finish();
	    }
		
		try {
			place = new PlaceManager(this).getPlace(idPlaceSelected);
		} catch (PlaceNotInLocal e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		mapView = (MapView) findViewById(R.id.map_viev);
		

		GeoPoint center = toGeoPoint(place.getPosition());
		
		mapView.setBuiltInZoomControls(true);
		//mapView.setStreetView(true);
		mapController = mapView.getController();	
		mapController.setZoom(inicialZoom);
		mapController.setCenter(center);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());

		draw();

	}
		
	private void draw(){

		MyOverlay	overlay = new MyOverlay(getDrawableTypeSelected(place.getPlaceType()),this);
		
		OverlayItem item = new OverlayItem(toGeoPoint(place.getPosition()), place.getName(), place.getLongLocation());
		overlay.addOverlay(item);
		
		List<Overlay> mapOverlays = mapView.getOverlays();
		mapOverlays.add(overlay);
	}
	
	private void drawMyPosition(GeoPoint point){

		List<Overlay> mapOverlays = mapView.getOverlays();
		
		if(myPositoinOverlay != null)
			mapOverlays.remove(myPositoinOverlay);

		myPositoinOverlay = new MyOverlay(this.getResources().getDrawable(R.drawable.map_my_position));
		
		OverlayItem item = new OverlayItem(point, "My Position.","It's mi.");
		myPositoinOverlay.addOverlay(item);
		
		mapOverlays.add(myPositoinOverlay);

	}
	
	private Drawable getDrawableTypeSelected(PlaceType type){
		Drawable drawable;
		switch(type){
			case PUB:
				drawable = this.getResources().getDrawable(R.drawable.map_pub_selected);
				break;
			case CULTURAL: 
				drawable = this.getResources().getDrawable(R.drawable.map_cultural_selected);
				break;				 
			case HOTEL: 
				drawable = this.getResources().getDrawable(R.drawable.map_hotel_selected);
				break;
			case NATURAL:
				drawable = this.getResources().getDrawable(R.drawable.map_natural_selected);
				break;
			case DISCO:
				drawable = this.getResources().getDrawable(R.drawable.map_disco_selected);
				break;
			case CITY: 
				drawable = this.getResources().getDrawable(R.drawable.map_city_selected);
				break;
			case POI: 
				drawable = this.getResources().getDrawable(R.drawable.map_poi_selected);
				break;
			case CONTINENT:
			case COUNTRY: 
			case INFRASTRUCTURE:  
			case REGION: 
			case RESTAURANT: 
			default:
					drawable = this.getResources().getDrawable(R.drawable.map_default_marker);
		}
		return drawable;
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	public void asyncNotice(AsyncNoticeCode code) {
		
	}

	@Override
	public Activity getActivity() {
		return this;
	}

	@Override
	public void syncStarted() {
	}

	@Override
	public void syncEnded() {
		// TODO Auto-generated method stub
		
	}
	
	private GeoPoint toGeoPoint(Geopoint point){
		Double lat = point.getLatitude()*1E6;
		Double lon = point.getLongitude()*1E6;
		
		return new GeoPoint(lat.intValue(), lon.intValue());
	}
	
	public class MyOverlay extends ItemizedOverlay<OverlayItem>{
		
		private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
		private Context mContext = null;
			
		public MyOverlay(Drawable defaultMarker, Context context) {
			super(boundCenterBottom(defaultMarker));
			mContext = context;
		}
		
		public MyOverlay(Drawable defaultMarker) {
			super(boundCenterBottom(defaultMarker));
		}

		public void addOverlay(OverlayItem overlay) {
		    mOverlays.add(overlay);
		    populate();
		}

		@Override
		protected boolean onTap(int index) {
			if(mContext !=null){
			  OverlayItem item = mOverlays.get(index);
			  AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
			  dialog.setTitle(item.getTitle());
			  dialog.setMessage(item.getSnippet());
			  dialog.setNegativeButton("Cerar", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {

					dialog.dismiss();
				}
			});
			  dialog.show();
			}
			return true;
		}

		@Override
		protected OverlayItem createItem(int i) {
			
			return mOverlays.get(i);
		}

		@Override
		public int size() {

			return mOverlays.size();
		}
	}
	
	public class GeoUpdateHandler implements LocationListener{

		@Override
		public void onLocationChanged(Location location) {
			int lat = (int) (location.getLatitude() *1E6);
			int lon = (int) (location.getLongitude() *1E6);
			
			GeoPoint point = new GeoPoint(lat, lon);
			
			drawMyPosition(point);
			mapView.invalidate();
		}

		@Override
		public void onProviderDisabled(String provider) {
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			
		}
		
	}

	@Override
	public void syncAndWaitCallStarted() {
		
	}

	@Override
	public void syncAndWaitCallEnded(Object o, int syncAction) {
		
	}

}
